"""This module contains classes and functions related to prime numbers."""

"""Project Euler Solutions Library

Copyright (c) 2011 by Robert Vella - robert.r.h.vella@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

import math
from euler.core import LazyEvaluatedList, infinity   

def sieve_of_eratosthenes(maxn):    
    """Generates all primes <= [maxn]."""
    
    #Dictionary which maps pre-calculated prime composites to the primes which
    #have been identified as their factors. 
    prime_composites = {}  
    
    #For all 2 <= n <= maxn.  
    for n in range(2, maxn + 1):
        #If n is present in prime_composites, then n is prime.
        if n not in prime_composites:
            yield n       
            prime_composites[n * n] = [n] 
        else:
            #Otherwise, add n to each of those primes which have 
            #been previously identified as its factors. Store these values in 
            #the prime_composites dictionary.
            for prime in prime_composites[n]: 
                prime_composites.setdefault(prime + n, []).append(prime)
            
            #Once a prime composite has been processed, it is no longer needed.
            del prime_composites[n] 
    



        
class Primes(LazyEvaluatedList):
    """A cached list of primes."""
    
    def __init__(self, known_primes = list(sieve_of_eratosthenes(20)),
                    precal = 0):
        LazyEvaluatedList.__init__(self, known_primes, precal)
    
    #Override.
    def _next_item(self, last_result, number_of_known_terms):
        for n in infinity(last_result + 1):
            if isprime(n, self):
                return n
    
    #Override.
    def _precalculate(self, precal):
        self._replace_known_terms(list(sieve_of_eratosthenes(precal)))

def isprime(n, primes = Primes()):
    """Generates all primes <= [maxn].
    
    Optional Parameters:
        primes - An already active prime cache 
                    (See: euler.numbers.primes.Primes), as this algorithm 
               depends on the generation of prime numbers, passing an instance
               of Primes, with a number of pre-generated results, will actually
               reduce execution time. New primes generated within this function
               will also be added to the cache.
    """
    
    #Return true if [n] is present in the cache.
    if n < primes[-1]:
        if n in primes.terms():
            return True
        else:
            return False
    
    #Return false if [n] is divisable by any prime <= sqrt([n])        
    maxn = math.sqrt(n)
    current_prime_index = 0
    current_prime = primes[current_prime_index]
    
    while current_prime <= maxn:
        if n % current_prime == 0:
            return False
        
        current_prime_index += 1
        current_prime = primes[current_prime_index]
    
    return True


def prime_factors(n, primes = None): 
    """Returns the prime factors of [n].
    
    Optional Parameters:
        primes - An already active prime cache 
                    (See: euler.numbers.primes.Primes), as this algorithm 
               depends on the generation of prime numbers, passing an instance
               of Primes, with a number of pre-generated results, will actually
               reduce execution time. New primes generated within this function
               will also be added to the cache.
    
    Note:
        This function will not return unique values. If a prime occurs more 
        than once in the composition of a number, all its instances are 
        returned.
        
    Example:
        n = 24: [2, 2, 2, 3]
    """
    #Initialise primes cache if Mone is passed.
    primes = primes or Primes()   
    
    #If [n] is greater than 1, return the first prime number by which [n]
    #is divisable, concatenated to the prime factors of the quotient of [n] and
    #this prime number.
    return (n > 1 and next([prime] + prime_factors(n / prime, primes) 
                for prime in primes if n % prime == 0)) or []
     
    

